package com.chaosj.html.markdown;

import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.StrUtil;
import com.chaosj.html.markdown.entity.ScrapeArticle;
import com.google.common.base.Splitter;
import com.google.common.io.FileWriteMode;
import com.google.common.io.Files;
import lombok.SneakyThrows;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @className: StorageApi
 * @description:
 * @author: caoyangjie
 * @date: 2021/12/26
 **/
public class StorageApi {

    @SneakyThrows
    public static void storageScrapeTarget(ScrapeArticle article){
        File storageFile = new File(StrUtil.format("{}/{}-list.scrape", StorageFacade.storagePath(), LocalDate.now().toString() ));
        Files.createParentDirs(storageFile);
        Files.asByteSink(storageFile, FileWriteMode.APPEND).write(article.toString().getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 存储 转换的 HTML 到本地 目录
     * @param title
     * @param content
     */
    @SneakyThrows
    public static void storageContent(String basePath, String title, String content ){
        File storageFile = new File(StrUtil.format("{}/{}/README.md",basePath, title));
        Files.createParentDirs(storageFile);
        Files.write(content.getBytes(StandardCharsets.UTF_8), storageFile);
    }

    @SneakyThrows
    public static void storageImage(String imageStoragePath, String imagePath, String imageUrl){
        // 构造URL
        URL url = new URL(imageUrl);
        // 打开URL连接
        URLConnection con = url.openConnection();
        // 得到URL的输入流
        InputStream input = con.getInputStream();
        // 设置数据缓冲
        byte[] bs = new byte[1024 * 2];
        // 读取到的数据长度
        int len;
        // 输出的文件流保存图片至本地
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        while ((len = input.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        List<String> imageNames = Splitter.on("/").splitToList(imagePath);
        imageStoragePath = StrFormatter.format("{}/{}",imageStoragePath, imageNames.stream().skip(1).collect(Collectors.joining("/")));
        Files.createParentDirs(new File(imageStoragePath));
        if( imageStoragePath.endsWith(".svg") ){
            writeSvg2Png(os.toByteArray(), imageStoragePath.substring(0,imageStoragePath.length()-4)+".png");
        }else{
            Files.write(os.toByteArray(), new File(imageStoragePath));
        }
        os.close();
        input.close();
    }

    public static void writeSvg2Png(byte[] svgCodes, String pngFilePath){
        try(FileOutputStream fileOutputStream = new FileOutputStream(new File(pngFilePath))){
            PNGTranscoder t = new PNGTranscoder();
            TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(svgCodes));
            TranscoderOutput output = new TranscoderOutput( fileOutputStream );
            t.transcode(input, output);
            fileOutputStream.flush();
        } catch (FileNotFoundException e) {
        } catch (TranscoderException e) {
        } catch (IOException e) {
        } finally {
        }
    }

    /**
     * 将svg字符串转换为png
     *
     * @param svgCode svg代码
     * @param pngFilePath 保存的路径
     * @throws TranscoderException svg代码异常
     * @throws IOException io错误
     */
    public static void convertToPng(String svgCode, String pngFilePath) throws IOException,
            TranscoderException {

        File file = new File(pngFilePath);

        FileOutputStream outputStream = null;
        try {
            file.createNewFile();
            outputStream = new FileOutputStream(file);
            convertToPng(svgCode, outputStream);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 将svgCode转换成png文件，直接输出到流中
     *
     * @param svgCode svg代码
     * @param outputStream 输出流
     * @throws TranscoderException 异常
     * @throws IOException io异常
     */
    public static void convertToPng(String svgCode, OutputStream outputStream)
            throws TranscoderException, IOException {
        try {
            byte[] bytes = svgCode.getBytes("utf-8");
            PNGTranscoder t = new PNGTranscoder();
            TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(bytes));
            TranscoderOutput output = new TranscoderOutput(outputStream);
            t.transcode(input, output);
            outputStream.flush();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
